package cn.pangza.user.service.impl;

import cn.pangza.common.redis.service.RedisService;
import cn.pangza.user.constant.UserRedisKeyConstant;
import cn.pangza.user.entity.po.SystemUserPo;
import cn.pangza.user.entity.vo.SystemUserVo;
import cn.pangza.user.service.SecurityService;
import cn.pangza.user.utils.SecurityUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.stream.Collectors;

public class SecurityServiceImpl implements SecurityService {

    @Autowired
    RedisService redisService;

    @Override
    public boolean hasAnyPermission(String permission) {
        boolean flag = false;
        SystemUserPo principal = SecurityUtil.getCurrentSystemUserPo();
        if(ObjectUtils.isEmpty(principal)) {
            principal = (SystemUserPo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        String systemUserVoString = redisService.get(UserRedisKeyConstant.USER_INFO + principal.getId());
        SystemUserVo systemUserVo = (SystemUserVo) JSONObject.parseObject(systemUserVoString, SystemUserVo.class);
        List<String> permissionList = systemUserVo.getPermission().stream().filter(item -> !item.startsWith("ROLE_")).collect(Collectors.toList());
        for (int i = 0; i < permissionList.size(); i++) {
            String current = permissionList.get(i);
            if(current.equals(permission)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    @Override
    public boolean hasAnyRole(String role) {
        boolean flag = false;
        SystemUserPo principal = SecurityUtil.getCurrentSystemUserPo();
        if(ObjectUtils.isEmpty(principal)) {
            principal = (SystemUserPo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        String systemUserVoString = redisService.get(UserRedisKeyConstant.USER_INFO + principal.getId());
        SystemUserVo systemUserVo = (SystemUserVo) JSONObject.parseObject(systemUserVoString, SystemUserVo.class);
        List<String> roleList = systemUserVo.getPermission().stream().filter(item -> item.startsWith("ROLE_")).collect(Collectors.toList());
        for (int i = 0; i < roleList.size(); i++) {
            String current = roleList.get(i);
            if(current.equals(role)) {
                flag = true;
                break;
            }
        }
        return flag;
    }


}
